package com.alperez.androidsmscamera.model;

import org.json.JSONException;
import org.json.JSONObject;

import com.alperez.androidsmscamera.model.ParsedCommandAbstract.ParseCommandResult;

/**
 * This encapsulates raw SMS request data along with parsed command and the time,
 * this command was received
 * @author Stas
 *
 */
public class SmsRequest {
	private long timeReceived;
	private String rawData;
	private ParseCommandResult parseCommandResult = ParseCommandResult.NOT_PARSED;
	private String requestPassword;
	private ParsedCommandAbstract command;
	
	public void reset() {
		timeReceived = 0;
		rawData = null;
		parseCommandResult = ParseCommandResult.NOT_PARSED;
		command = null;
	}
	
	public long getTimeReceived() {
		return timeReceived;
	}
	
	public void setTimeReceived(long timeReceived) {
		this.timeReceived = timeReceived;
	}

	public String getRawData() {
		return rawData;
	}

	public ParseCommandResult setRawData(String rawData) {
		this.rawData = rawData;
		parseCommandResult = this.parseRawData();
		return parseCommandResult;
	}
	
	private ParseCommandResult parseRawData() {
		try {
			JSONObject jData = new JSONObject(this.rawData);
			requestPassword = jData.optString("password", null);
			String commandMessage = jData.getString("message");
			return SmsRequest.parseCommand(this, commandMessage);
		} catch (JSONException e) {
			command = null;
			return ParseCommandResult.ERROR_WRONG_FORMAT;
		}
	}

	public ParsedCommandAbstract getCommand() {
		return (parseCommandResult == ParseCommandResult.PARSED_OK) ? command : null;
	}

	public ParseCommandResult getParseCommandResult() {
		return parseCommandResult;
	}

	public String getRequestPassword() {
		return requestPassword;
	}

	
	
	/**
	 * This method parses command JSON from SMS. As a result - command field of SmsRequest is set up.
	 * parsing result is not set up for SmsRequest but returned as a result
	 * @param smsRequest
	 * @param cmdMessage
	 * @return
	 * @throws JSONException
	 */
	private static ParseCommandResult parseCommand(SmsRequest smsRequest, String cmdMessage) throws JSONException {
		//TODO parse all commands here
	}
	
	

}
